<template>
  <el-cascader
    ref="selectDeptUser"
    style="width: 100%"
    v-model="selectedValues"
    :options="treeData"
    :props="treeProps"
    :show-all-levels="false"
    filterable
    :disabled="disabled"
    clearable
    @change="handleChange"
  />
</template>

<script setup>
import {deptTreeSelect} from '@/api/system/dept'
import {nextTick, onMounted, reactive, ref, watch} from 'vue'

// 定义组件 props
const props = defineProps({
  options: {
    type: Object,
    default: () => ({})
  },
  // 使用modelValue以符合Vue3的v-model规范
  modelValue: {
    type: [Array, String, Number],
    default: () => ''
  },
  resultProps: {
    type: Object,
    default: () => ({})
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

// 定义组件 emits
const emit = defineEmits(['update:modelValue', 'change'])

// 组件引用
const selectDeptUser = ref(null)

// 响应式状态
const selectedValues = ref(props.modelValue)
const treeData = ref([])

// 树形配置
const treeProps = reactive({
  value: 'id',
  label: 'name',
  emitPath: false,
  multiple: false,
  checkStrictly: true
})

const resultPropsValue = reactive({
  name: 'name',
  id: 'id'
})

// 监听 modelValue 变化，同步到 selectedValues
watch(
  () => props.modelValue,
  (newVal) => {
    let convertedVal = newVal;
    if (typeof newVal === 'number' && !isNaN(newVal)) {
      convertedVal = String(newVal);
    }
    selectedValues.value = convertedVal;
  },
  {
    deep: true,
    immediate: true
  }
)

// 监听 selectedValues 变化，触发 update:modelValue 事件（Vue3的v-model更新方式）
watch(
  () => selectedValues.value,
  (newVal) => {
    emit('update:modelValue', newVal)
  }
)

// 挂载后初始化配置
onMounted(() => {
  init()
})

// 初始化方法：合并配置
const init = () => {
  Object.assign(resultPropsValue, props.resultProps)
  Object.assign(treeProps, props.options)
  deptTreeSelect().then(res => {
    treeData.value = res
  })
}

// 处理选择变化事件
const handleChange = (value) => {
  nextTick(() => {
    emit('change', value)
  })
}
</script>

<style scoped></style>